package com.qinglei.recoup.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;

/**
 * 时间工具类
 */
@Slf4j
public class DateUtil {

    public static final String FULL_DATE_PATTERN = "yyyyMMdd";
    public static final String FULL_TIME_PATTERN = "yyyyMMddHHmmss";
    public static final String FULL_TIME_MILLI_PATTERN = "yyyyMMddHHmmssSSS";

    public static final String FULL_TIME_MILLI_BAR_PATTERN = "yyyy-MM-dd-HH-mm-ss-SSS";

    public static final String FULL_TIME_SPLIT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String FULL_TIME_CHS_PATTERN = "yyyy年MM月dd日 HH:mm:ss";

    public static String formatFullTime(LocalDateTime localDateTime) {
        return formatFullTime(localDateTime, FULL_TIME_PATTERN);
    }

    public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return localDateTime.format(dateTimeFormatter);
    }

    private static String getDateFormat(Date date, String dateFormatType) {
        SimpleDateFormat simformat = new SimpleDateFormat(dateFormatType);
        return simformat.format(date);
    }

    public static String formatCSTTime(String date, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date d = sdf.parse(date);
        return DateUtil.getDateFormat(d, format);
    }

    /**
     * 检查当前时间是否处于指定时间段
     *
     * @param startTime 格式：03:30
     * @param endTime   格式：04:00
     * @return
     */
    public static boolean isCurTimePeriod(String startTimeStr, String endTimeStr) {
        LocalTime nowTime = LocalTime.now();
        LocalDate nowDate = LocalDate.now();
        LocalTime startTime = LocalTime.parse(startTimeStr);
        LocalTime endTime = LocalTime.parse(endTimeStr);
        if (startTime.isBefore(endTime)) {
            // 开始和结束时间在同一天
            if (nowTime.isAfter(startTime) && nowTime.isBefore(endTime)) {
                return true;
            }
        } else {
            LocalDateTime nowDateTime = LocalDateTime.of(nowDate, nowTime);
            LocalDateTime startDateTime = LocalDateTime.of(nowDate, startTime);
            LocalDateTime endDateTime = LocalDateTime.of(nowDate.plusDays(1), endTime);
            // 结束时间在后一天
            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                return true;
            }
            // 开始时间在前一天
            startDateTime = LocalDateTime.of(nowDate.minusDays(1), startTime);
            endDateTime = LocalDateTime.of(nowDate, endTime);
            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将秒时间 格式化为 X小时X分钟
     *
     * @param seconds
     * @return
     */
    public static String formatHourMinute(Integer seconds) {
        int minute = Math.round(seconds / 60f);
        int hour = minute / 60;
        minute = minute % 60;
        StringBuilder builder = new StringBuilder();
        if (hour != 0) {
            builder.append(hour).append("小时");
        }
        builder.append(minute).append("分钟");
        return builder.toString();
    }

    /**
     * 将秒时间 格式化为 X小时X分钟X秒
     *
     * @param seconds
     * @return
     */
    public static String formatHourMinuteSecond(Integer time) {
        int minutes = time / 60;
        int seconds = time % 60;
        int hours = minutes / 60;
        minutes = minutes % 60;
        StringBuilder builder = new StringBuilder();
        if (hours != 0) {
            builder.append(hours).append("小时");
        }
        if (hours != 0 || minutes != 0) {
            builder.append(minutes).append("分钟");
        }
        builder.append(seconds).append("秒");
        return builder.toString();
    }

    /**
     * 字符串时间段转为秒
     * @param str 时间段格式  时:分:秒 或 时:分
     * @param defVal
     * @return
     */
    public static Integer str2Second(String str, Integer defVal) {
        Integer secondVal = defVal;
        try {
            LocalTime time = LocalTime.parse(str);
            secondVal = time.toSecondOfDay();
        } catch (Exception e) {
            log.warn("str2Second error str:{}", str, e);
        }
        return secondVal;
    }


    public static  String getTimes(Integer second){
        StringBuilder dateTimes = new StringBuilder();
        int h = second / 3600;
        if(h>=1){
            dateTimes.append(h+"小时");
        }
        int m =(second - h*3600)/60;
        if(m>=1){
            dateTimes.append(m+"分钟");
        }
        int s =second-h*3600-m*60;
        if(s>=1){
            dateTimes.append(s+"秒");
        }

       return  dateTimes.toString();
    }

    public static List<String> getBetweenDate(String start, String end) {
            List<String> list = new ArrayList<>();
            LocalDate startDate = LocalDate.parse(start);
            LocalDate endDate = LocalDate.parse(end);
            long distance = ChronoUnit.DAYS.between(startDate, endDate);
            if (distance < 1) {
                return list;
            }
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f.toString()));
            return list;
    }

    /**
     *
     * @param a
     * @param b
     * @return
     */
    public static long getTimeDifference(LocalTime a, LocalTime b) {

        long c = a.getSecond()+a.getHour()*3600+a.getMinute()*60;
        long d = b.getSecond()+b.getHour()*3600+b.getMinute()*60;
        long e = Math.abs(c-d);
        long f = 12 * 3600;
        if(e > f){
            return  Math.abs(e - 24*3600)/60 ;
        }else {
            return e/60;
        }
    }
}
